using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UI.BankingPanel.Data;

/// <summary>
/// Excel数据导出器
/// 支持将押注数据导出为Excel格式（CSV格式，兼容Excel）
/// 兼容安卓平台
/// </summary>
public static class ExcelExporter
{
    /// <summary>
    /// 导出押注数据到Excel文件
    /// </summary>
    /// <param name="bankingData">银行数据</param>
    /// <param name="fileName">文件名（不含扩展名）</param>
    /// <returns>导出结果信息</returns>
    public static ExportResult ExportBankingDataToExcel(BankingData bankingData, string fileName = null)
    {
        return ExportBankingDataToExcel(bankingData, fileName, ExportFormat.Detailed);
    }
    
    /// <summary>
    /// 导出押注数据到Excel文件（支持格式选择）
    /// </summary>
    /// <param name="bankingData">银行数据</param>
    /// <param name="fileName">文件名（不含扩展名）</param>
    /// <param name="format">导出格式</param>
    /// <returns>导出结果信息</returns>
    public static ExportResult ExportBankingDataToExcel(BankingData bankingData, string fileName, ExportFormat format)
    {
        try
        {
            if (bankingData == null)
            {
                return new ExportResult(false, "数据为空，无法导出");
            }

            // 生成文件名
            if (string.IsNullOrEmpty(fileName))
            {
                fileName = $"押注数据_{DateTime.Now:yyyyMMdd_HHmmss}";
            }

            // 获取导出路径
            string filePath = GetExportPath(fileName + ".csv");
            
            // 生成CSV内容
            string csvContent = GenerateCSVContent(bankingData, format);
            
            // 写入文件
            File.WriteAllText(filePath, csvContent, Encoding.UTF8);
            
            Debug.Log($"[ExcelExporter] 数据导出成功: {filePath}");
            
            return new ExportResult(true, $"导出成功！\n文件路径: {filePath}", filePath);
        }
        catch (Exception ex)
        {
            Debug.LogError($"[ExcelExporter] 导出失败: {ex.Message}\n{ex.StackTrace}");
            return new ExportResult(false, $"导出失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 生成CSV格式内容
    /// </summary>
    /// <param name="bankingData">银行数据</param>
    /// <param name="format">导出格式</param>
    /// <returns>CSV内容字符串</returns>
    private static string GenerateCSVContent(BankingData bankingData, ExportFormat format = ExportFormat.Detailed)
    {
        var sb = new StringBuilder();
        
        // 添加BOM以支持中文显示
        sb.Append('\uFEFF');
        
        // 标题和时间
        sb.AppendLine("押注数据导出报表");
        sb.AppendLine($"导出时间,{DateTime.Now:yyyy-MM-dd HH:mm:ss}");
        sb.AppendLine($"赔率,{bankingData.odds}");
        sb.AppendLine();
        
        // 统计数据汇总
        var stats = bankingData.GetStatisticsData();
        sb.AppendLine("=== 数据汇总 ===");
        sb.AppendLine("项目,金额");
        sb.AppendLine($"总数据,{stats.revenueTotal}");
        sb.AppendLine($"自己吃码,{stats.eatCodeTotal}");
        sb.AppendLine($"上报数据,{stats.reportTotal}");
        sb.AppendLine();
        
        // 根据导出格式生成不同内容
        switch (format)
        {
            case ExportFormat.Summary:
                GenerateSummaryContent(sb, bankingData);
                break;
            case ExportFormat.Categorized:
                GenerateCategorizedContent(sb, bankingData);
                break;
            case ExportFormat.Detailed:
            default:
                GenerateDetailedContent(sb, bankingData);
                break;
        }
        
        return sb.ToString();
    }

    /// <summary>
    /// 生成汇总格式内容
    /// </summary>
    /// <param name="sb">字符串构建器</param>
    /// <param name="bankingData">银行数据</param>
    private static void GenerateSummaryContent(StringBuilder sb, BankingData bankingData)
    {
        // 只显示汇总数据，不显示详细号码
        sb.AppendLine("=== 汇总报表 ===");
        sb.AppendLine("数据类型,金额");
        
        var stats = bankingData.GetStatisticsData();
        sb.AppendLine($"总押注,{stats.revenueTotal}");
        sb.AppendLine($"自己吃码,{stats.eatCodeTotal}");
        sb.AppendLine($"上报数据,{stats.reportTotal}");
        sb.AppendLine($"净收益,{stats.eatCodeTotal - stats.reportTotal}");
    }

    /// <summary>
    /// 生成分类格式内容
    /// </summary>
    /// <param name="sb">字符串构建器</param>
    /// <param name="bankingData">银行数据</param>
    private static void GenerateCategorizedContent(StringBuilder sb, BankingData bankingData)
    {
        // 按您的示例格式分类显示
        sb.AppendLine("=== 分类统计 ===");
        
        // 总数据部分
        sb.AppendLine("总数据");
        sb.AppendLine("号码,押注金额");
        var totalDataNumbers = GetNumbersWithData(bankingData.GetAllNumberBetData(), DataType.Total);
        foreach (var item in totalDataNumbers)
        {
            sb.AppendLine($"{item.Key:D2},{item.Value}");
        }
        sb.AppendLine();
        
        // 自己吃码部分
        sb.AppendLine("自己吃码");
        sb.AppendLine("号码,吃码金额");
        var eatCodeNumbers = GetNumbersWithData(bankingData.GetAllNumberBetData(), DataType.EatCode);
        foreach (var item in eatCodeNumbers)
        {
            sb.AppendLine($"{item.Key:D2},{item.Value}");
        }
        sb.AppendLine();
        
        // 上报数据部分
        sb.AppendLine("上报数据");
        sb.AppendLine("号码,上报金额");
        var reportNumbers = GetNumbersWithData(bankingData.GetAllNumberBetData(), DataType.Report);
        foreach (var item in reportNumbers)
        {
            sb.AppendLine($"{item.Key:D2},{item.Value}");
        }
    }

    /// <summary>
    /// 生成详细格式内容
    /// </summary>
    /// <param name="sb">字符串构建器</param>
    /// <param name="bankingData">银行数据</param>
    private static void GenerateDetailedContent(StringBuilder sb, BankingData bankingData)
    {
        // 分类统计
        GenerateCategorizedContent(sb, bankingData);
        
        sb.AppendLine();
        
        // 详细数据表格
        sb.AppendLine("=== 详细数据 ===");
        sb.AppendLine("号码,总押注,自己吃码,上报数据,风险值");
        
        foreach (var betData in bankingData.GetAllNumberBetData())
        {
            // 只显示有数据的号码
            if (betData.totalBetAmount > 0 || betData.selfBetAmount > 0 || betData.reportAmount > 0)
            {
                sb.AppendLine($"{betData.number:D2},{betData.totalBetAmount},{betData.selfBetAmount},{betData.reportAmount},{betData.riskValue:F2}");
            }
        }
    }

    /// <summary>
    /// 获取有数据的号码列表
    /// </summary>
    /// <param name="allData">所有号码数据</param>
    /// <param name="dataType">数据类型</param>
    /// <returns>号码和对应数值的字典</returns>
    private static Dictionary<int, float> GetNumbersWithData(List<NumberBetData> allData, DataType dataType)
    {
        var result = new Dictionary<int, float>();
        
        foreach (var betData in allData)
        {
            float value = 0;
            switch (dataType)
            {
                case DataType.Total:
                    value = betData.totalBetAmount;
                    break;
                case DataType.EatCode:
                    value = betData.selfBetAmount;
                    break;
                case DataType.Report:
                    value = betData.reportAmount;
                    break;
            }
            
            if (value > 0)
            {
                result[betData.number] = value;
            }
        }
        
        return result;
    }

    /// <summary>
    /// 获取导出文件路径
    /// </summary>
    /// <param name="fileName">文件名</param>
    /// <returns>完整文件路径</returns>
    private static string GetExportPath(string fileName)
    {
        string exportDir;
        
        #if UNITY_ANDROID && !UNITY_EDITOR
            // 安卓平台：使用外部存储的Downloads目录
            exportDir = Path.Combine(Application.persistentDataPath, "Exports");
        #else
            // 其他平台：使用持久化数据目录
            exportDir = Path.Combine(Application.persistentDataPath, "Exports");
        #endif
        
        // 确保目录存在
        if (!Directory.Exists(exportDir))
        {
            Directory.CreateDirectory(exportDir);
        }
        
        return Path.Combine(exportDir, fileName);
    }

    /// <summary>
    /// 获取导出目录路径
    /// </summary>
    /// <returns>导出目录路径</returns>
    public static string GetExportDirectory()
    {
        #if UNITY_ANDROID && !UNITY_EDITOR
            return Path.Combine(Application.persistentDataPath, "Exports");
        #else
            return Path.Combine(Application.persistentDataPath, "Exports");
        #endif
    }

    /// <summary>
    /// 数据类型枚举
    /// </summary>
    private enum DataType
    {
        Total,      // 总数据
        EatCode,    // 吃码
        Report      // 上报
    }
}

/// <summary>
/// 导出格式枚举
/// </summary>
public enum ExportFormat
{
    Summary,        // 汇总格式（只显示总计数据）
    Categorized,    // 分类格式（按类别显示号码数据）
    Detailed        // 详细格式（包含所有信息）
}

/// <summary>
/// 导出结果类
/// </summary>
public class ExportResult
{
    public bool Success { get; private set; }
    public string Message { get; private set; }
    public string FilePath { get; private set; }

    public ExportResult(bool success, string message, string filePath = null)
    {
        Success = success;
        Message = message;
        FilePath = filePath;
    }
} 